import 'package:enjoy_plus/utils/eventbus.dart';
import 'package:enjoy_plus/utils/http.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:enjoy_plus/utils/token.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class MinePage extends StatefulWidget {
  const MinePage({super.key, required this.currentIndex});

  final int currentIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "images/visitor_profile_icon@2x.png",
    }
  ];

  Map userInfo = {
    'id': null,
    'avatar': null,
    'nickName': null,
  };

  // 获取用户信息
  _getUserInfo() async {
    if (TokenManager().getToken() != null) {
      final res = await http.get('/userInfo');
      setState(() {
        userInfo = res['data'];
      });
    }
  }

  @override
  void initState() {
    super.initState();
    // 事件总线2：订阅（注册/绑定）事件
    eventBus.on<RefreshMine>().listen((event) {
      _getUserInfo();
    });
  }

  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 1) {
      _getUserInfo();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text(
          '我的',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                // Navigator.pushNamed(context, '/profile');
              },
              child: Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(50.0),
                    child: userInfo['avatar'] != null
                        ? Image.network(
                            userInfo['avatar'],
                            width: 50,
                            height: 50,
                          )
                        : Image.asset(
                            'assets/images/avatar_1.jpg',
                            width: 50,
                            height: 50,
                          ),
                  ),
                  const SizedBox(width: 10),
                  Text(userInfo['nickName'] ?? '未登录用户',
                      style:
                          const TextStyle(fontSize: 16, color: Colors.white)),
                  const Spacer(),
                  GestureDetector(
                    onTap: () {
                      Navigator.pushNamed(
                        context,
                        '/profile',
                        arguments: userInfo,
                      );
                    },
                    child: const Text(
                      '去完善信息',
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                  const Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.white,
                    size: 13,
                  )
                ],
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin:
                const EdgeInsets.only(top: 20, left: 10, right: 10, bottom: 20),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: menuList.map(
                (item) {
                  return SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        Row(
                          children: [
                            Image.asset(
                              item['icon'],
                              width: 20,
                              height: 20,
                            ),
                            const SizedBox(
                              width: 10,
                            ),
                            Text(
                              item['title'],
                              style: const TextStyle(fontSize: 16),
                            )
                          ],
                        ),
                        const Spacer(),
                        const Icon(
                          Icons.arrow_forward_ios,
                          size: 12,
                          color: Colors.grey,
                        )
                      ],
                    ),
                  );
                },
              ).toList(),
            ),
          ),
          // 测试持久化
          FilledButton(
            onPressed: () async {
              // final prefs = await SharedPreferences.getInstance();
              // prefs.setString('token', '123456');
              TokenManager().saveToken('-----test token-----');
              ToastUtil.showInfo('存储成功');
            },
            child: const Text('测试持久化-存token'),
          ),
          FilledButton(
            onPressed: () async {
              // final prefs = await SharedPreferences.getInstance();
              // String token = prefs.getString('token') ?? '';
              String token = TokenManager().getToken() ?? '';
              ToastUtil.showInfo('取到的token为：$token');
            },
            child: const Text('测试持久化-取token'),
          ),
          FilledButton(
            onPressed: () async {
              // final prefs = await SharedPreferences.getInstance();
              // prefs.remove('token');
              TokenManager().removeToken();
              ToastUtil.showInfo('删除成功');
            },
            child: const Text('测试持久化-删除token'),
          ),
          FilledButton(
            onPressed: () {
              Navigator.pushNamed(context, '/profile');
            },
            child: const Text('去个人信息页'),
          ),
          FilledButton(
            onPressed: () async {
              final res = await http.get('/userInfo');
              print(res);
            },
            child: const Text('测试需要带 token 的请求'),
          ),
          FilledButton(
            onPressed: () async {
              final ImagePicker picker = ImagePicker();
              // Pick an image.
              final XFile? image =
                  await picker.pickImage(source: ImageSource.gallery);
              print(image?.path);
            },
            child: const Text('访问相册'),
          ),
        ],
      ),
    );
  }
}
